﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using MvcEngine.Core;
using MvcEngine.Mvc.Models.ViewModels;
using MvcEngine.Mvc.StarterSite.Controllers;
using MvcEngine.Core.Localization;
using MvcEngine.Mvc.Extensions;
using MvcEngine.HtmlText.Repositories;
using MvcEngine.HtmlText.Models;
using MvcEngine.HtmlText.Models.Entities;
using MvcEngine.Mvc.Filters;
using MvcEngine.Mvc;
using System.Web;
using MvcEngine.Core.Exceptions;
using MvcEngine.Core.Extensions;
using System.IO;
using MvcEngine.Core.Helpers;
using MvcEngine.Core.Configuration;
using MvcEngine.HtmlText.Components.Extensions;
using System.Globalization;
using MvcEngine.Mvc.Controllers;
using MvcEngine.HtmlText.Managers;
using MvcEngine.Mvc.Models;
using MvcEngine.Core.Pagination;
using MvcEngine.Mvc.Results;

namespace MvcEngine.HtmlText.BackOffice.Controllers
{
    public class TextController : BaseController
    {
        private IHtmlTextRepository repository = null;

        public TextController(IHtmlTextRepository repository)
        {
            this.repository = repository;
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel Edit(int ctrId)
        {
            HtmlTextItem item = IoC.Resolve<IHtmlTextRepository>().Get(ctrId);
            string content = string.Empty;

            if (item == null)
            {
                item = IoC.Resolve<HtmlTextItem>();
                item.PageContentId = ctrId;
            }

            return new MvcEngineModelItem<HtmlTextItem>()
            {
                Item = item,
                ViewName = "Edit"
            };
        }

        [ValidateInput(false)]
        [AntiForgeryValidationFilter]
        [AcceptVerbs(HttpVerbs.Post)]
        public object Save(int ctrId, HtmlTextItem item)
        {
            if (ModelState.IsValid)
            {
                item.PageContentId = ctrId;
                repository.Save(item);

                return Json(new { model = "valid" });
            }

            return Json(new { model = "invalid", errors = ModelState.GetErrors() });
        }


        [ValidateInput(false)]
        [AntiForgeryValidationFilter]
        [AcceptVerbs(HttpVerbs.Post)]
        public MvcEngineModel UploadFile(HttpPostedFileBase file, string content, int ctrId)
        {
            if (file == null)
                throw new BusinessException("Uploaded file can't be null.");

            string directory = PrepareDirectory(ctrId);
            string fileName = file.FileName.UrlEncode();
            string filePath = directory + Path.DirectorySeparatorChar + fileName;
            string fileExtension = Path.GetExtension(fileName).Remove(0, 1);

            if (!FileHelper.Current.Exists(filePath))
                file.SaveAs(filePath);

            ExtensionConfigurationElement element = ConfigurationUtil.Current.Extensions.GetElement(fileExtension);
            string value = null;

            if (element == null || element.Type != "image")
            {
                string tag = "<p><a href=\"{0}\">{1}</a></p>";
                string text = fileName + " (" + FileHelper.Current.SizeFormat(file.ContentLength, "N") + ")";
                value = content + string.Format(tag, Url.HtmlTextFile(ctrId, fileName), text);
            }
            else
            {
                value = content + "<img src=\"" + Url.HtmlTextFile(ctrId, fileName) + "\" alt=\"" + file.FileName + "\"/>";
            }
            ModelState["Content"].Value = new ValueProviderResult(value, value, CultureInfo.CurrentCulture);

            return Edit(ctrId);
        }

        #region Protected methods

        protected virtual string PrepareDirectory(int ctrId)
        {
            string directoryPath = ConfigurationUtil.Current.ModulesFolder + Path.DirectorySeparatorChar +
                this.HttpContext.Items["moduleName"].ToString() +
                Path.DirectorySeparatorChar + "Content" + Path.DirectorySeparatorChar + ctrId.ToString();

            DirectoryHelper.Current.CheckFolder(directoryPath);
            return directoryPath;
        }

        #endregion
    }
}
